package com.lmx.web.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.HttpRequestUtil;
import com.lmx.common.util.PropertiesFileUtil;
import com.lmx.common.wxpay.GetWxOrderno;
import com.lmx.common.wxpay.RequestHandler;
import com.lmx.persistence.service.DataProcessService;
import com.lmx.persistence.service.MessageService;
import com.lmx.persistence.service.PayRecordService;
import com.lmx.persistence.service.PayService;
import com.lmx.persistence.service.RechargeService;
import com.lmx.persistence.service.UserService;
import com.lmx.persistence.service.WeiXinService;
import com.lmx.repoDomain.tmodel.PayPageInfo;
import com.lmx.repoDomain.tmodel.WeChatInfo;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/wechat")
public class WCPayController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private Properties properties = PropertiesFileUtil.getApplicationProperties();

	@Autowired
	PayService payService;

	@Autowired
	RechargeService rechargeService;

	@Autowired
	UserService userService;

	@Autowired
	MessageService messageSerive;

	@Autowired
	PayRecordService payRecordService;

	@Autowired
	DataProcessService dataProcessService;
	
	@Autowired
	WeiXinService weiXinService;

	@Autowired
	HttpServletRequest request;

	@Autowired
	HttpServletResponse response;

	// /**
	// * 跳转微信支付操作页面
	// *
	// * @param values
	// * @return
	// */
	// @RequestMapping(value = "/goPayPage", method = RequestMethod.GET)
	// public String goPayPage(ModelMap model,PayPageInfo info) {
	// String appid = properties.getProperty("weixin.appId"); // 微信appid
	//
	// // 支付请求地址
	// String redirect_uri = "";
	//
	// // scope 参数视各自需求而定，这里用scope=snsapi_base 不弹出授权页面直接授权目的只获取统一支付接口的openid
	// String url = "";
	// try {
	// url = properties.getProperty("weixin.oauth2Code") + appid +
	// "&redirect_uri="
	// + URLEncoder.encode(redirect_uri, "UTF-8")
	// // + redirect_uri
	// + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
	// } catch (UnsupportedEncodingException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// model.put("url", url);//跳转到url
	// return null;// 不跳转
	// }

	/**
	 * 微信支付
	 * 
	 * @param payOrder
	 * @throws Exception
	 * @throws SQLException
	 * @throws Exception
	 */
	@RequestMapping(value = "/wcPay")
	private String createWeixinPayRequest(ModelMap model, PayPageInfo info) throws Exception {
		String code = request.getParameter("code");// huibati
		int total_fee = (int) (info.getFee() * 100);// 金额

		String appid = properties.getProperty("weixin.appId");
		String appsecret = properties.getProperty("weixin.appSecret");
		String partner = properties.getProperty("weixin.partner"); // 微信支付商户号
		String partnerkey = properties.getProperty("weixin.partnerkey"); // 微信支付商户密钥

		String openId = "";
		String url = properties.getProperty("weixin.oauth2OpenId");
		String returnData = HttpRequestUtil.sendGet(url,
				"appid="+appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code");
		if (returnData == null) {
			// setErrorMessage("获取微信授权出错1!");
			// AppLogger.getInstance().infoLog("获取微信授权出错1!");
			return "";
		} else {
			JSONObject json = JSONObject.fromObject(returnData);
			if (json.containsKey("errcode")) {
				// setErrorMessage("获取微信授权出错!");
				// AppLogger.getInstance().infoLog("获取微信授权出错3!=====" + res);
				return "";
			}
			if ("".equals(json.get("openid"))) {
				// setAjaxJavascript("location.href='/index';");
				return "";
			}
			openId = (String) json.get("openid");
		}

		// 获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder
		String currTime = CommonUtil.getCurrTime();
		String strTime = currTime.substring(8, currTime.length());
		String strRandom = CommonUtil.buildRandom(4) + "";
		String strReq = strTime + strRandom;

		String mch_id = partner;
		String nonce_str = strReq;
		String body = "账户充值";
		String attach = "royalpalmpolo";
		String out_trade_no = String.valueOf(info.getUid());
		String spbill_create_ip = dataProcessService.getIpAddr(request);
		String notify_url = properties.getProperty("weixinpay.callback_url");

		String trade_type = "JSAPI";
		String openid = openId;
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);
		packageParams.put("attach", attach);
		packageParams.put("out_trade_no", out_trade_no);

		packageParams.put("total_fee", total_fee + "");
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", notify_url);

		packageParams.put("trade_type", trade_type);
		packageParams.put("openid", openid);

		RequestHandler reqHandler = new RequestHandler(request, response);
		reqHandler.init(appid, appsecret, partnerkey);

		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<mch_id>" + mch_id + "</mch_id>" + "<nonce_str>"
				+ nonce_str + "</nonce_str>" + "<body><![CDATA[" + body + "]]></body>" + "<attach>" + attach
				+ "</attach>" + "<out_trade_no>" + out_trade_no + "</out_trade_no>" + "<total_fee>" + total_fee
				+ "</total_fee>" + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" + "<notify_url>"
				+ notify_url + "</notify_url>" + "<trade_type>" + trade_type + "</trade_type>" + "<openid>" + openid
				+ "</openid>" + "<sign>" + sign + "</sign>" + "</xml>";
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		String prepay_id = GetWxOrderno.getPayNo(createOrderURL, xml);
		if (prepay_id.equals("")) {
			// setErrorMessage("统一支付接口获取预支付订单出错");
			return "";// 主页
		}
		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String appid2 = appid;
		String timestamp = CommonUtil.create_timestamp();
		String nonceStr2 = nonce_str;
		String prepay_id2 = "prepay_id=" + prepay_id;
		String packages = prepay_id2;
		finalpackage.put("appId", appid2);
		finalpackage.put("timeStamp", timestamp);
		finalpackage.put("nonceStr", nonceStr2);
		finalpackage.put("package", packages);
		finalpackage.put("signType", "MD5");
		String finalsign = reqHandler.createSign(finalpackage);

		model.put("appid", appid2);
		model.put("timestamp", timestamp);
		model.put("nonceStr", nonceStr2);
		model.put("package", packages);
		model.put("sign", finalsign);

		model.put("showUrl", properties.getProperty("weixinpay.show_url"));
		return "page/wechat/wcPay";//
	}

	@RequestMapping("/paycallback")
	@ResponseBody
	public void payNotify(HttpServletRequest request) {
		logger.debug("----------------------------- 微信支付返回-------------------------------------");
		BufferedReader in = null;
		String result = "";
		try {

			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			logger.debug("payment : " + result);
		} catch (Exception e) {
			logger.debug("payment : " + e.toString());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		SortedMap map = payRecordService.XmlToSortedMap(result);
		if ("SUCCESS".equals(map.get("result_code"))) {// 成功
			logger.debug("充值成功 : " + map.get("total_fee"));
			// map.get("total_fee")
		}
		// 签名验证
	}

	
    //testScan
    @RequestMapping(value = "/testScan", method = RequestMethod.GET)

    public String  test() {

        return "page/wechat/testScan";
    } 
	
    //testScan
    @RequestMapping(value = "/getWeChatData", method = RequestMethod.GET)
    @ResponseBody
    public String  getAdminUser() {
    	String json = "";
    	Map<String ,Object> msgMap = new HashMap<String ,Object>();
    	
    	WeChatInfo data = new WeChatInfo();
        //data=weiXinService.sign("http://api.tnb99.cn/wechat/testScan");//http://124.42.9.27:7080   http://web.tnb99.cn/index.html#/business/mainpage/scanQRCode
    	data=weiXinService.sign("http://api.tnb99.cn/wechat/testScan");
    	msgMap.put("appId", data.getAppId());
    	msgMap.put("timestamp",data.getTimeStamp());
    	msgMap.put("nonceStr", data.getNonceStr());
    	msgMap.put("signature", data.getSignature());
      	msgMap.put("jsapiT", data.getJsapiTicket());
    	
    	json = CommonUtil.mapToJsonString(msgMap);
        return json;
    }   
	
}
